package jst.householdmanager.activities;

import java.util.ArrayList;
import java.util.List;

import jst.householdmanager.GlobalFunc;
import jst.householdmanager.R;
import jst.householdmanager.activities.EditPurchaseListPosAct.EditPurchaseListAction;
import jst.householdmanager.database.ItemCategoriesDataSource;
import jst.householdmanager.database.ItemsDataSource;
import jst.householdmanager.database.Items_in_ItemCategoriesDataSource;
import jst.householdmanager.database.PurchaseListPosDataSource;
import jst.householdmanager.database.ShopsDataSource;
import jst.householdmanager.database.Shops_has_ItemsDataSource;
import jst.householdmanager.database.table.ItemCategories;
import jst.householdmanager.database.table.Items;
import jst.householdmanager.database.table.PurchaseListPos;
import jst.householdmanager.database.table.Shops;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;

public class WorkPurchaseListAct extends Activity {
	public enum WorkPurchaseListAction {
		PROCESS_PURCHASE, SHOW_HISTORY;
	}

	private static final int EDIT_PURLISTPOS_ACT_EDIT = 1000;

	private List<Integer> itemCatspinnerIdList = new ArrayList<Integer>();
	private List<Integer> shopspinnerIdList = new ArrayList<Integer>();
	private ArrayList<ListEntryPurchaseListPos.EntryRecord> purchaseListPos;
	private WorkPurchaseListAction actionId;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_workpurchaselist);
		getActionBar().setDisplayHomeAsUpEnabled(true);

		Bundle givenData = getIntent().getExtras();

		if (givenData != null) {
			this.actionId = (WorkPurchaseListAction) givenData.get("ActionId");
		} else {
			this.actionId = WorkPurchaseListAction.SHOW_HISTORY;
		}

		EditText itemlist_search = ((EditText) findViewById(R.id.workpurchaselist_search));
		itemlist_search.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				WorkPurchaseListAct.this.loadItemList();
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});

		// fill spinners
		this.fillSpinners();

		ListView itemlist_list = (ListView) findViewById(R.id.workpurchaselist_list);
		itemlist_list.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parentView, View selectedItemView, int position, long id) {
				if (WorkPurchaseListAct.this.actionId == WorkPurchaseListAction.PROCESS_PURCHASE) {
					Intent intent = new Intent(WorkPurchaseListAct.this, EditPurchaseListPosAct.class);
					intent.putExtra("ItemId", WorkPurchaseListAct.this.purchaseListPos.get(position).id);
					intent.putExtra("FinDate", GlobalFunc.StringToDate("0000-00-00"));
					intent.putExtra("ActionId", EditPurchaseListAction.PROCESS_PURCHASE);
					startActivityForResult(intent, EDIT_PURLISTPOS_ACT_EDIT);
				}
			}
		});
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			onBackPressed();
			break;
		default:
			return super.onOptionsItemSelected(item);
		}
		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == Activity.RESULT_OK && requestCode == EDIT_PURLISTPOS_ACT_EDIT) {
			Bundle resultBundle = data.getExtras();
			if (resultBundle.getBoolean("dataChanged")) {
				this.loadItemList();
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void fillSpinners() {
		// fill ItemCategories spinner element
		List<String> itemCategoriesName = new ArrayList<String>();
		itemCategoriesName.add(getText(R.string.all).toString());
		this.itemCatspinnerIdList.add(0);

		List<ItemCategories> itemCategories = ItemCategoriesDataSource.readAll();

		for (ItemCategories itemCategory : itemCategories) {
			itemCategoriesName.add(itemCategory.getName());
			this.itemCatspinnerIdList.add(itemCategory.getId());
		}
		Spinner spin_ItemCategories = (Spinner) findViewById(R.id.workpurchaselist_spinner_itemcategory);
		ArrayAdapter<String> itemCategoriesAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, itemCategoriesName);
		spin_ItemCategories.setAdapter(itemCategoriesAdapter);

		spin_ItemCategories.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
				WorkPurchaseListAct.this.loadItemList();
			}

			@Override
			public void onNothingSelected(AdapterView<?> parentView) {
				return;
			}
		});

		// fill Shop spinner element
		List<String> shopName = new ArrayList<String>();
		shopName.add(getText(R.string.all).toString());
		this.shopspinnerIdList.add(0);

		List<Shops> shops = ShopsDataSource.readAll();

		for (Shops shop : shops) {
			shopName.add(shop.getName());
			this.shopspinnerIdList.add(shop.getId());
		}
		Spinner spin_Shops = (Spinner) findViewById(R.id.workpurchaselist_spinner_shop);
		ArrayAdapter<String> shopsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, shopName);
		spin_Shops.setAdapter(shopsAdapter);

		spin_Shops.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
				WorkPurchaseListAct.this.loadItemList();
			}

			@Override
			public void onNothingSelected(AdapterView<?> parentView) {
				return;
			}
		});
	}

	private void loadItemList() {
		int itemCategoryId = WorkPurchaseListAct.this.itemCatspinnerIdList.get(((Spinner) findViewById(R.id.workpurchaselist_spinner_itemcategory))
				.getSelectedItemPosition());
		int shopId = WorkPurchaseListAct.this.shopspinnerIdList.get(((Spinner) findViewById(R.id.workpurchaselist_spinner_shop))
				.getSelectedItemPosition());

		ListEntryPurchaseListPos listEntryPurchaseListPos = new ListEntryPurchaseListPos(this);
		this.purchaseListPos = new ArrayList<ListEntryPurchaseListPos.EntryRecord>();

		String searchText = ((EditText) findViewById(R.id.workpurchaselist_search)).getText().toString();

		String selection = null;

		switch (this.actionId) {
		case PROCESS_PURCHASE:
			selection = " = ?";
			break;
		case SHOW_HISTORY:
			selection = " != ?";
			break;
		}

		for (PurchaseListPos purchaseListPos : PurchaseListPosDataSource.readAll(PurchaseListPosDataSource.COLUMN_FINISH_DATE + selection,
				new String[] { GlobalFunc.DateToString(null) })) {
			Boolean selectionOk = true;
			// selection ItemCategorie
			if ((itemCategoryId != 0) && (Items_in_ItemCategoriesDataSource.read(itemCategoryId, purchaseListPos.getItem_Id()) == null)) {
				selectionOk = false;
			}
			// selection Shop
			if (selectionOk && (shopId != 0) && (Shops_has_ItemsDataSource.read(shopId, purchaseListPos.getItem_Id()) == null)) {
				selectionOk = false;
			}
			// search text
			if (selectionOk) {
				Items item = ItemsDataSource.read(purchaseListPos.getItem_Id());
				if (GlobalFunc.Like(item.getName(), "%" + searchText + "%")) {
					this.purchaseListPos.add(listEntryPurchaseListPos.Record(purchaseListPos.getItem_Id(), purchaseListPos.getFinishDate(),
							item.getName(), Integer.toString(purchaseListPos.getAmount()), item.getDescription(), purchaseListPos.getComment()));
				}
			}
		}

		ListView purchaseList = (ListView) findViewById(R.id.workpurchaselist_list);
		purchaseList.setAdapter(listEntryPurchaseListPos.Adapter(this, android.R.layout.simple_list_item_1, this.purchaseListPos));
	}
}
